import { Injectable, HttpStatus } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { AuthService } from "./auth.service";
import { Strategy,ExtractJwt } from "passport-jwt";
import { JwtPayload } from "./interfaces/jwt.interface";
import { ApiException } from "../../CoreModule/exception/api.exception";
import { ApiErrorCode } from "../../ShareModule/enums/api-error-code";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy){
    constructor(private readonly authService:AuthService){
        super({
            jwtFromRequest:ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: 'gbblovetrf',
        })
    }

    async validate(payload:JwtPayload){
        const user = await this.authService.validateUser(payload);

        if(!user) throw new ApiException("未授权",ApiErrorCode.UNANTHORIZED,HttpStatus.UNAUTHORIZED);

        return user;
    }
}